<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- BIM专兼职人员配置台账 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData :searchData="searchArr" @search="search"></searchData>
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title"></title-name> -->
        <!-- 表格 -->
        <list-table
          ref="table"
          :pageKeys="['pageNum', 'pageSize', 'total']"
          :columns="columns"
          :request="loadData"
          :startIndex="0"
          :filterData="filterData"
          :statistics-config="{
            use: true, //是否统计，传false不会显示操作栏
            temp: statistics
          }"
          :exportPermission="{ select: 'BIM_004_exp_05', all: 'BIM_004_exp_05' }"
          :exportConfig="{ use: true, select: $route.meta.title, all: $route.meta.title }"
        >
          <!-- 新增 -->
          <a-button
            v-btnPermission="'BIM_004_add_01'"
            slot="prefix"
            class="mb12"
            icon="plus"
            type="primary"
            @click="handleManage(2)"
            >新增</a-button
          >
          <!-- 下载附件 -->
          <template slot="suffix" slot-scope="scoped">
            <a-button
              v-btnPermission="'BIM_004_dow_06'"
              :loading="downLoading"
              class="mb12"
              icon="cloud-download"
              :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
              type="primary"
              @click="downZip(scoped.selectedRowsMap)"
              >批量下载附件</a-button
            >
            <ExportExcel
              ref="exportExcel"
              :export-list="exportList"
              :loading="loadingExport"
              icon="export"
              :file-name="$route.meta.title + '模板.xlsx'"
              button-text="下载导入模板"
              :beforeDownload="beforeDownload"
            />
            <ExcelImportButton
              ref="excelImportButton"
              :loading="loadingImport"
              icon="import"
              button-text="批量导入"
              @handleSubmit="handleImport"
              v-if="hideBuquBtn()"
            />
          </template>
          <template slot="evidence" slot-scope="text, record">
            <a
              v-if="text === 1"
              @click="
                selectRow = record
                editModel = 0
                visible = true
              "
              >有</a
            >
            <span v-else>无</span>
          </template>
          <template slot="actions" slot-scope="text, record">
            <MoreButton>
              <template v-if="record.fileInfoList && record.fileInfoList.length > 0">
                <a
                  v-btnPermission="'BIM_004_loo_02'"
                  @click="
                    editModel = 3
                    fileList = record.fileInfoList
                    visible = true
                  "
                  >查看附件({{ record.fileInfoList ? record.fileInfoList.length : 0 }})</a
                >
                <!-- <a v-btnPermission="'BIM_004_loo_02'" @click="handleManage(0, record)">查看</a> -->
                <a-divider v-btnPermission="'BIM_004_loo_02'" type="vertical"></a-divider>
              </template>
              <a v-btnPermission="'BIM_004_edi_03'" @click="handleManage(1, record)">编辑</a>
              <template>
                <a-divider v-btnPermission="'BIM_004_del_04'" type="vertical"></a-divider>
                <a v-btnPermission="'BIM_004_del_04'" class="del_btn" @click="handleRemove(record.id, search)">删除</a>
              </template>
            </MoreButton>
          </template>
        </list-table>
      </a-card>
    </div>
    <!-- 查看附件 -->
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      edit-model="V"
      :width="1000"
      :headerTitle="editModel !== 0 ? '查看附件' : '查看证书'"
      :fileList="editModel !== 0 ? fileList : []"
    >
      <!-- 查看证书 -->
      <b-table
        v-if="editModel === 0"
        slot="formHeader"
        ref="tableDialogForm"
        :pageKeys="['pageNum', 'pageSize', 'total']"
        :columns="columnsTwo"
        :request="loadDataTwo"
      ></b-table>
    </DialogForm>
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
  </base-breadcrumb>
</template>

<script>
import {
  getPageBimFullPartLedger,
  getPageBimPersonnelObtainEvidenceLedger,
  deleteBimFullPart,
  getBimFullPartLedgerSummary,
  insertBimFullPartLedgerBatch
} from '@/api/bimIntegrate/bimResource.js'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import BasePage from '@/views/basePage'
import DialogForm from '@/components/DialogForm' // 弹窗
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import { isPhone } from '@/utils/regExpression' // 正则校验
import OrgTreeSelect from '@/components/OrgTreeSelect'
const searchArr = [
  {
    name: '单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '单位',
  //   valueKey: 'unitId',
  //   type: SelectCompanyAndProject,
  //   extraParams: {
  //     notContainTags: ['PD']
  //   }
  // },
  {
    name: '类别',
    type: 'select',
    value: 'category',
    data: [
      {
        label: '信息化',
        value: 0
      },
      {
        label: 'BIM',
        value: 1
      }
    ]
  },
  // 搜索框
  {
    name: '姓名',
    type: 'input',
    value: 'userName'
  },
  {
    name: '专/兼职',
    type: 'select',
    value: 'fullPart',
    data: [
      {
        label: '专职',
        value: 0
      },
      {
        label: '兼职',
        value: 1
      }
    ]
  },
  {
    name: '取证情况',
    type: 'select',
    value: 'evidence',
    data: [
      {
        label: '无',
        value: 0
      },
      {
        label: '有',
        value: 1
      }
    ]
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    isHidden: true,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '单位',
    ellipsis: true,
    dataIndex: 'unitName'
  },
  {
    title: '部门/项目',
    ellipsis: true,
    dataIndex: 'deptName'
  },
  {
    title: '类别',
    ellipsis: true,
    dataIndex: 'category',
    minWidth: '80px',
    customRender() {
      return ['信息化', 'BIM'][arguments[0]] || '无'
    },
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    },
    options: ['信息化', 'BIM']
  },
  {
    title: '专/兼职',
    ellipsis: true,
    dataIndex: 'fullPart',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    },
    options: ['专职', '兼职'],
    customRender() {
      return ['专职', '兼职'][arguments[0]] || '无'
    }
  },
  {
    title: '姓名',
    ellipsis: true,
    dataIndex: 'userName',
    minWidth: '80px',
  },
  {
    title: '员工编号',
    ellipsis: true,
    dataIndex: 'employeeNum'
  },
  {
    title: '联系方式',
    ellipsis: true,
    dataIndex: 'phone'
  },
  {
    title: '取证情况',
    ellipsis: true,
    align: 'center',
    dataIndex: 'evidence',
    scopedSlots: { customRender: 'evidence' },
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    },
    options: ['无', '有']
  },
  {
    title: '更新时间',
    width: 180,
    isHidden: true,
    ellipsis: true,
    dataIndex: 'modifiedTime'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    isHidden: true,
    width: '230px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'actions' }
  }
]
const columnsTwo = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    isHidden: true,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '类别',
    ellipsis: true,
    dataIndex: 'category',
    customRender() {
      return ['信息化', 'BIM'][arguments[0]] || '无'
    }
  },
  {
    title: '证书名称',
    ellipsis: true,
    dataIndex: 'name',
    customRender() {
      return arguments[1].certificateGrade && arguments[1].certifiedAgency
        ? arguments[1].certifiedAgency + arguments[1].certificateGrade
        : ''
    }
  },
  {
    title: '取证时间',
    ellipsis: true,
    dataIndex: 'evidenceTime'
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    DialogForm,
    ExportResult,
    ExportExcel
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      columnsTwo,
      queryParam: {}, // 查询参数
      editModel: 0, // 操作类型：0 查看取证；1 编辑；2 新增；3 查看附件
      visible: false, // 查看附件弹窗控件
      visibleExport: false, // 导入结果弹窗控件
      exportList: [{ columns: [], datas: [] }], // 导入配置项
      fileList: [], // 当前文件列表
      loadingImport: false, // 导入loading
      loadingExport: false, // 导出loading
      countInfo: {}, // 汇总数据
      countList: [
        {
          title: '信息化：',
          value: 'info'
        },
        {
          title: 'BIM：',
          value: 'bim'
        },
        {
          title: '专职：',
          value: 'full'
        },
        {
          title: '兼职：',
          value: 'part'
        }
      ],
      removeApi: { remove: deleteBimFullPart }, // 删除台账
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
        return getPageBimFullPartLedger(requestParameters).then((res) => {
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, total: res.data?.total }
          }
        })
      },
      loadDataTwo: (parameter) => {
        const requestParameters = Object.assign({}, parameter, { param: { userId: this.selectRow.userId } })
        return getPageBimPersonnelObtainEvidenceLedger(requestParameters).then((res) => {
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, total: res.data?.total }
          }
        })
      },
      selectRow: {}, // 选中项
      importCheck: {
        单位: 'unitName',
        '部门/项目': 'deptName',
        类别: 'category',
        '专/兼职': 'fullPart',
        姓名: 'userName',
        员工编号: 'employeeNum',
        联系方式: 'phone',
        取证情况: 'evidence'
      } // 导入字段对应
    }
  },
  watch: {
    // 监听姓名更新取证表格
    'selectRow.userId'(e) {
      e && this.$refs.tableDialogForm?.getData(null, true)
    }
  },
  methods: {
    /**
     * @description: 导出模板前的回调处理
     * @param {Promise} callback：导出方法
     */
    async beforeDownload() {
      let columnsExport = this.$clone(this.columns)
      // 设置默认导出配置项
      this.exportList = [
        {
          columns: columnsExport,
          datas: [
            {
              unitName: '所属单位'
            }
          ]
        }
      ]
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    async handleImport(e) {
      let form = []
      // 遍历校验表格字段，且添加表单
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remark') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            // 校验手机号
            if (item === 'phone' && !isPhone.test(keys[i])) {
              this.$message.warning(`第${Number(index) + 1}行${i}格式错误`)
              return
            }
            let formatArray = {
              fullPart: { 专职: 0, 兼职: 1 },
              evidence: { 无: 0, 有: 1 },
              category: { 信息化: 0, BIM: 1 }
            } // 转义数组
            // 转义专兼职，取证情况，类别
            if (item === 'fullPart' || item === 'evidence' || item === 'category') {
              listItem[item] = formatArray[item][keys[i]]
            } else {
              listItem[item] = keys[i]
            }
          }
        }
      }
      // 开始导入
      this.loadingImport = true
      const importRes = await insertBimFullPartLedgerBatch(form).catch(() => {
        this.loadingImport = false
      })
      this.loadingImport = false
      // 导入成功
      if (importRes?.code === '0') {
        if (importRes.data?.list?.length > 0) {
          // 配置导出项，且打开导出结果
          let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
          // 格式化取证情况
          columnsExport[7].customRender = function () {
            return ['无', '有'][arguments[0]] || '无'
          }
          // 表头添加失败原因
          columnsExport.push({
            dataIndex: 'failureReason',
            ellipsis: true,
            title: '失败原因'
          })

          this.exportList = [
            {
              successCount: importRes.data.successCount,
              columns: columnsExport,
              datas: importRes.data.list
            }
          ]
          this.visibleExport = true
        } else {
          this.$message.success('导入成功')
        }
        // 如果有导入成功条数，则刷新表格
        importRes.data?.successCount > 0 && this.search()
      }
    },
    /**
     * 格式话数据
     */
    filterData(datas) {
      let list = this.$clone(datas)
      list.forEach((item, index) => {
        item.index = index + 1
        item.fullPart = ['专职', '兼职'][item.fullPart]
        item.evidence = ['无', '有'][item.evidence]
        item.category = ['信息化', 'BIM'][item.category]
      })
      return list
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.getData(null, true)
    },
    /**
     * 汇总请求
     */
    getSummary() {
      getBimFullPartLedgerSummary({ param: this.queryParam }).then((res) => {
        if (res.code === '0') {
          this.countInfo = res.data
        }
      })
    },
    /**
     * 汇总
     */
    statistics() {
      return this.countList.map((item, index) => (
        <span key={index}>
          {item.title}
          <a>
            <b>{this.countInfo?.[item.value] || 0}</b>
          </a>
          个{index % 2 === 0 ? '，' : ''}
          {index == 1 && <span style="color:#40a9ff;margin-top:-3px;padding:0 12px;font-weight:bolder">|</span>}
        </span>
      ))
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      let query = {
        editModel: type
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/bimResource/staffingConfigEdit',
        query
      })
    }
  }
}
</script>
